package org.example.forum.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotNull;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.config.AppConfig;
import org.example.forum.model.User;
import org.example.forum.services.IUserService;
import org.example.forum.utils.MD5Util;
import org.example.forum.utils.StringUtil;
import org.example.forum.utils.UUIDUtil;
import org.springframework.web.bind.annotation.*;

//对controller进行api说宁
@Tag(name="用户接口")
@RestController
@Slf4j
//路由映射  一级映射 
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    /**
     * 用户注册
     * @param username 用户名
     * @param nickname 用户昵称
     * @param password 密码
     * @param passwordRepeat 重复密码
     * @return 
     */
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public AppResult register( @Parameter(description = "用户名", required = true)
                                   @RequestParam("username") @NotNull String username,
                               @Parameter(description = "用户昵称", required = true)
                                   @RequestParam("nickname") @NonNull String nickname,
                               @Parameter(description = "密码", required = true)
                                   @RequestParam("password") @NotNull String password,
                               @Parameter(description = "重复密码", required = true)
                                   @RequestParam("passwordRepeat") @NotNull String passwordRepeat){
        

//        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(nickname)
//        || StringUtil.isEmpty(password) || StringUtil.isEmpty(passwordRepeat)){
//            //返回错误信息
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }

        //校验密码与重复密码是否一致
        if(!password.equals(passwordRepeat)){
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //处理密码
        //生成盐
        String salt = UUIDUtil.UUID_32();
        //生成加密的密码
        String encryptPassword = MD5Util.md5Salt(password,salt) ;
        //设置密码
        user.setPassword(encryptPassword);
        //设置盐
        user.setSalt(salt);

        //调用Service层
        userService.createNormalUser(user);
        return AppResult.success();
    }

    /**
     * 用户登陆
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public AppResult login( HttpServletRequest request,
                            @Parameter(description = "用户名", required = true)
                                @RequestParam("username") @NonNull String username,
                            @Parameter(description = "密码", required = true)
                            @RequestParam("password") @NonNull String password){
        //调用Service中的登录方法
        User user = userService.login(username,password);
        if(user == null){
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //返回结果
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //如果成功就把对象写入session
        HttpSession session = request.getSession();
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success();
        
    }

    /**
     * 获取用户信息
     * @param request 
     * @param id 用户Id
     * @return
     */
    @Operation(summary = "用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @Parameter(description = "用户Id")
                                       @RequestParam(value = "id",required = false)  Long id){
        //定义返回的user对象
        User user = null;
        //根据id的值判断对象的获取方式
        if(id == null){
            //如果过当前id为空 则从session中获取用户信息
            HttpSession session = request.getSession(false);
            //从session中获取用户信息 类型强转  l
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else{
            //id不为空，从数据库中查询用户信息
            user = userService.selectById(id);
        }
        //查用户对象是否为空
        if(user == null) {
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //不为空 返回用户对象
        return AppResult.success(user);
    }

    @Operation(summary = "退出登录")
    @GetMapping("/logout")
    public AppResult logOut(HttpServletRequest request){
        //获取session
        HttpSession session = request.getSession();
        if(session != null){
            //用户登录状态下 退出登录 
            log.info("退出成功");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }


    /**
     * 修改个人信息
     * @param username 用户名
     * @param nickname 昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNum 电话号
     * @param remark 个人简介
     * @return AppResult
     */ 
    @Operation(summary = "修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo (HttpServletRequest request,
                                 @Parameter(description = "用户名") @RequestParam(value = "username",required = false) String username,
                                 @Parameter(description = "昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                 @Parameter(description = "性别") @RequestParam(value = "gender",required = false) Byte gender,
                                 @Parameter(description = "邮箱") @RequestParam(value = "email",required = false) String email,
                                 @Parameter(description = "电话号") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                 @Parameter(description = "个人简介") @RequestParam(value = "remark",required = false) String remark) {
        // 1. 接收参数
        // 2. 对参数做非空校验（全部都为空，则返回错误描述）
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {
            // 返回错误信息
            return AppResult.failed("请输入要修改的内容");
        }

        // 从session中获取用户Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 3. 封装对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户Id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个人简介

        // 4. 调用Service中的方法
        userService.modifyInfo(updateUser);
        // 5. 查询最新的用户信息
        user = userService.selectById(user.getId());
        // 6. 把最新的用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 7. 返回结果
        return AppResult.success(user);
    }

    @Operation(summary = "修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request,
                                     @Parameter(description = "原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                     @Parameter(description = "新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                     @Parameter(description = "确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 1. 校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat)) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 2. 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 3. 调用Service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        // 4. 销毁session
        if (session != null) {
            session.invalidate();
        }
        // 5. 返回结果
        return AppResult.success();
    }

 }
